package com.kancy.springcloudconfig.util;

import com.kancy.springcloudconfig.constants.Constants;
import org.springframework.security.crypto.encrypt.Encryptors;

public class CipherUtil {

    private static String DEFAULT_TEMPLATE = "{cipher}%s";

    public static String encrypt(String data,String password, String salt){
        return Encryptors.text(password, salt).encrypt(data);
    }
    public static String encrypt(String data,String password){
        return encrypt(data,password, Constants.DEFAULT_CIPHER_SALT);
    }

    public static String encrypt(String data){
        return encrypt(data, Constants.DEFAULT_CIPHER_PASSWORD, Constants.DEFAULT_CIPHER_SALT);
    }

    public static String decrypt(String data,String password, String salt){
        if(data != null && data.startsWith("{cipher}")){
            data = data.substring(8);
        }
        return Encryptors.text(password, salt).decrypt(data);
    }

    public static String decrypt(String data,String password){
        return decrypt(data,password, Constants.DEFAULT_CIPHER_SALT);
    }

    public static String decrypt(String data){
        return decrypt(data, Constants.DEFAULT_CIPHER_PASSWORD, Constants.DEFAULT_CIPHER_SALT);
    }

    public static String format(String result){
        return String.format(DEFAULT_TEMPLATE, result);
    }
}
